package com.mirror.llk.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.mirror.llk.bean.domain.TTheme;
import com.mirror.llk.bean.request.ThemePublishRequest;
import com.mirror.llk.bean.response.ThemePublishResponse;
import com.mirror.llk.logic.ThemeLogic;
import com.mirror.llk.utils.CommonUtil;
import com.mirror.llk.utils.Constant;
import com.mirror.llk.utils.Interface;
import com.mirror.utils.base.BaseTask;
import com.mirror.utils.io.FileUtils;

public class ThemePublishTask extends BaseTask {

	private static final String TAG = "ThemePublishTask";

	private Long localId;

	private Context context;

	private ThemePublishResponse response;

	private ThemeLogic logic = new ThemeLogic();

	public ThemePublishTask(Context context, Long localId) {
		this.context = context;
		this.localId = localId;
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			// 获取主题目录
			String themePath = logic.getLocalThemeDir(localId);
			// 压缩主题图片并编码
			File zipFile = FileUtils.zipDir(themePath, Constant.IMAGE.PREFIX, Constant.IMAGE.SUFFIX, String.valueOf(localId));
			String themeImage = FileUtils.readEncryptFile(new FileInputStream(zipFile));
			// 查询本地主题
			TTheme theme = logic.queryLocaTheme(localId);
			// 发布主题
			response = logic.publishTheme(new ThemePublishRequest(theme, themeImage));
		}
		catch (IOException e) {
			Log.i(TAG, "发布主题发生输入输出流异常", e);
			response = new ThemePublishResponse(Interface.ERROR_CODE_1000);
		}
		return super.doInBackground(params);
	}

	@Override
	protected void onPostExecute(String result) {
		if (CommonUtil.handleError(context, response)) {
			Toast.makeText(context, "发布成功", Toast.LENGTH_SHORT).show();
		}
	}
}
